package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.Admin;
import com.example.service.IAdminService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: lfanh
 * Date: 2022/11/4 13:57
 * @author Administrator
 */

@RestController
@RequestMapping("admin")
public class AdminController  {

    @Autowired
    private IAdminService iAdminService;

    /*
    * 管理员登录
    * */

    @PostMapping("login")
    public R<Admin> login(HttpServletRequest request, @RequestBody Admin admin){

        //1、将页面提交的密码进行md5加密处理
        String password = admin.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据提交的登录名查询数据库
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getAdminName,admin.getAdminName());
        Admin ad = iAdminService.getOne(queryWrapper);

        //3、未查询出该用户则返回登录失败
        if(ad == null){
            return R.error("登录失败！");
        }
        //4、校验密码，不一致则返回登录失败
        if(! ad.getPassword().equals(password)){
            return R.error("登录失败！");
        }
        //5、验证管理员账号状态是否异常
        if(ad.getStatus() != 1){
            return R.error("该账号已被禁用！");
        }

        //6、登录成功，将管理员id存入Session并返回登录成功
        request.getSession().setAttribute("admin",ad.getId());
        return R.success(ad);
    }


    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        //清理当前Session中保存的管理员id
        request.getSession().removeAttribute("admin");
        return R.success("退出成功");

    }
}
